#include <stdlib.h>
#include <string.h>
#include "common.h"

gint current_color = 0;

void
tb_start_element(GMarkupParseContext * context,
		 const gchar * element_name,
		 const gchar ** attribute_names,
		 const gchar ** attribute_values,
		 gpointer user_data, GError ** error)
{
	CopticWindow *win = (CopticWindow *) user_data;

	if (g_ascii_strcasecmp(element_name, "t") == 0)
		return;
	else if (g_ascii_strcasecmp(element_name, "b") == 0)
		wattron(win->ncwin, A_BOLD);
	else if (g_ascii_strcasecmp(element_name, "u") == 0)
		wattron(win->ncwin, A_BOLD);
	else if (g_ascii_strcasecmp(element_name, "dim") == 0)
		wattron(win->ncwin, A_DIM);
	else if (g_ascii_strcasecmp(element_name, "blink") == 0)
		wattron(win->ncwin, A_BLINK);
	else if (g_ascii_strcasecmp(element_name, "reverse") == 0)
		wattron(win->ncwin, A_REVERSE);
	else if (g_ascii_strcasecmp(element_name, "color") == 0 &&
		 g_ascii_strcasecmp(*attribute_names, "n") == 0) {
		current_color = atoi(*attribute_values);
		wattron(win->ncwin, COLOR_PAIR(current_color));
	}
}


void
tb_end_element(GMarkupParseContext * context,
	       const gchar * element_name, gpointer user_data, GError ** error)
{
	CopticWindow *win = (CopticWindow *) user_data;

	if (g_ascii_strcasecmp(element_name, "t") == 0) {
		wattrset(win->ncwin, A_NORMAL);
		current_color = 0;
	} else if (g_ascii_strcasecmp(element_name, "b") == 0)
		wattroff(win->ncwin, A_BOLD);
	else if (g_ascii_strcasecmp(element_name, "u") == 0)
		wattroff(win->ncwin, A_BOLD);
	else if (g_ascii_strcasecmp(element_name, "dim") == 0)
		wattroff(win->ncwin, A_DIM);
	else if (g_ascii_strcasecmp(element_name, "blink") == 0)
		wattroff(win->ncwin, A_BLINK);
	else if (g_ascii_strcasecmp(element_name, "reverse") == 0)
		wattroff(win->ncwin, A_REVERSE);
	else if (g_ascii_strcasecmp(element_name, "color") == 0) {
		wattroff(win->ncwin, COLOR_PAIR(current_color));
		current_color = 0;
	}
}


void
tb_text(GMarkupParseContext * context,
	const gchar * text, gsize text_len, gpointer user_data, GError ** error)
{
	CopticWindow *win = (CopticWindow *) user_data;
	wchar_t *w_text;

	w_text = (wchar_t *) g_malloc(sizeof(wchar_t) * (text_len + 1));
	wchar_from_utf8(text, w_text, text_len);
	waddwstr(win->ncwin, w_text);
	refresh_if_topwin(win);
}

void
tb_error(GMarkupParseContext * context, GError * error, gpointer user_data)
{
	g_printerr("error: %s\n", error->message);
}

GMarkupParser parser =
	{ tb_start_element, tb_end_element, tb_text, tb_text, tb_error };


/*
 * Okey, initially we do this without wrapping and scroll support
 * because I got stuck with it for days and now I need to rest :(
 */

void
text_parser_insert(CopticWindow * win, gchar * text)
{
	GMarkupParseContext *parser_context = NULL;

	g_assert(win != NULL);

	parser_context =
		g_markup_parse_context_new(&parser, 0, (gpointer) win, FALSE);
	g_markup_parse_context_parse(parser_context, text, strlen(text), NULL);
}
